package com.zhf.testMetaData;

import com.zhf.utils.DruidUtils;
import org.junit.Test;

import java.sql.*;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/9/24 23:40
 */
public class TestMetaData {
    //获取数据库相关的元数据信息 使用DatabaseMetaData
    @Test
    public void testDatabaseMetaData() throws SQLException {
        //获取数据库连接
        Connection connection = DruidUtils.getConnection();

        //获取DatabaseMetaData
        DatabaseMetaData metaData = connection.getMetaData();

        System.out.println(metaData.getURL());
        System.out.println(metaData.getUserName());
        System.out.println(metaData.getDatabaseProductName());
        System.out.println(metaData.getDatabaseProductVersion());
        System.out.println(metaData.getDriverName());
        System.out.println(metaData.isReadOnly());
    }

    //获取结果集中元数据信息
    @Test
    public void testResultSetMetaData() throws SQLException {
        //获取数据库连接
        Connection connection = DruidUtils.getConnection();

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement("select * from employee");

        //执行SQL获取结果
        ResultSet resultSet = preparedStatement.executeQuery();

        //获取ResultSetMetaData
        ResultSetMetaData metaData = resultSet.getMetaData();

        System.out.println(metaData.getColumnCount());
        System.out.println(metaData.getColumnName(2));
        System.out.println(metaData.getColumnTypeName(2));
        //释放资源
        DruidUtils.close(connection,preparedStatement,resultSet);
    }
}
